/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import rule from "./rule";

/**
 * 
 * @param 
 * {form 数据规则{key:{value,reg(rule对应的key),min,max,requried,tag}}
    data 数据{key:value} 
    currentKey 当前需要检测key}  
 */
const check = ({ form, data = {}, currentKey = "" }) => {
  const tagReg = /请|输入|必|填/;
  let res = {
      code: 0,
      msg: "check:ok"
    },
    key;
  if (!form) {
    return res;
  }
  for (key in form) {
    if (currentKey && currentKey !== key) {
      continue;
    }
    let {
        value = data[key] || "",
        reg = "",
        min = "",
        max = "",
        required = true,
        tag,
        valueSize = 0
      } = form[key],
      { pattern, code, message, type = "string", tag: ruleTag } =
        (reg && rule[reg]) || {};
    //   使用rule规则中的tag
    tag = tag ? tag : ruleTag || "该项内容";
    //   检查tag中是否有关键字眼，确定是否追加后缀“不可为空”
    tag = tagReg.test(tag) ? tag : tag + "不可为空";
    if (required && !value) {
      res.code = 11;
      res.msg = tag;
      break;
    }
    if (value) {
      if (pattern && !pattern.test(value)) {
        //正则验证
        res.code = code;
        res.msg = message;
        break;
      } else {
        //长度 / 大小验证
        let arr = [];
        valueSize = 1 * (type === "number" ? value : value.length);
        if ((max && valueSize > max) || (min && valueSize < min)) {
          max && arr.push("小于等于" + max);
          min && arr.push("大于等于" + min);
          res.code = 12;
          res.msg =
            tag + (type === "number" ? "" : "长度") + "必须" + arr.join("且");
          break;
        }
      }
    }
  }
  if (currentKey && res.code === 0) {
    //单项验证通过后，返回批量验证结果
    return check({
      form,
      data
    });
  }
  // 验证结果判断是否增加errKey
  if (res.code > 0) {
    res.errKey = key;
  }
  return res;
};

export default check;
